//
//  SetLocationsRequest.m
//  NetMobileLocation
//
//  Created by Mehmet Sinan Şahin on 1/10/12.
//  Copyright (c) 2012 netgis. All rights reserved.
//

#import "SetLocationsRequest.h"
#import "SetLocationsResponse.h"
#import "NSString+Extensions.h"
#import "NSDate+Extensions.h"
#import "NGDBHelper.h"
#import "SharedPrefs.h"
#import "SoapFault.h"

@implementation SetLocationsRequest

@synthesize locationArray;

- (id) initWithLocations:(NSMutableArray *)locations {
    if (self = [super init]) {
        if ([NSString isEmpty:serviceUrl]) {
            serviceUrl = [SharedPrefs getServiceUrl];
        }        
        locationArray = locations;
    }
    return self;
}

#pragma mark - server post return handler

- (void) setLocationsHandler: (id) value {
    
    SetLocationsResponse *response = [SetLocationsResponse alloc];
    NSString *dateStr = [[NSDate date] toFormattedString];
	if([value isKindOfClass:[NSError class]]) {
		NSLog(@"SET LOCATIONs RESPONSE-->NSERROR.....%@", value);
        response = [response initWithError:value];
	} else if([value isKindOfClass:[SoapFault class]]) {
		NSLog(@"SET LOCATIONs RESPONSE-->SOAP FAULT.....%@", value);
        response = [response initWithSoapFault:value];
	} else {
        NSLog(@"SET LOCATIONs RESPONSE-->RETURN VALUE:\n%@\n%@\n", dateStr, (NSString *) value);
        response = [response initWithResponseXml:(NSString*)value];
    }
    if (![response isSuccessful]) {
        //setLocations zaten konumlar gönderilemediği zaman çağrılmalıdır.
        //Böyle bir durum olmaması gerekir !!
    } else {
        NGDBHelper *db = [NGDBHelper openDatabase];
        NSArray *array = [response getMessages];
        [db insertMessages:[response getMessages]];
        if ([array count] > 0) {
            //alert user for incoming messages
            [self alertMessageForMessageArriving:[array count]];
        }
        
        //Delete sent locations from database
        [db sendLocations:self.locationArray];
    }
    if (self.locationArray != nil) [self.locationArray release];
    [response release];
}

- (void)dealloc {
    if (self.locationArray != nil) [self.locationArray release];
    [super dealloc];
}

@end
